<template>
  <div class="register-container">
    <div class="register-card">
      <!-- 头部 -->
      <div class="register-header">
        <div class="logo">
          <img
            src="/images/logo.png"
            alt="CardCaptorSakura"
            class="logo-image"
          />
          <h1 class="logo-text">CardCaptorSakura</h1>
        </div>
        <p class="subtitle">创建您的账号，开始AI聊天之旅</p>
      </div>

      <!-- 注册表单 -->
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            size="large"
            prefix-icon="User"
            clearable
            @blur="checkUsernameAvailability"
          >
            <template #suffix>
              <el-icon v-if="usernameChecking" class="is-loading">
                <Loading />
              </el-icon>
              <el-icon
                v-else-if="usernameAvailable === true"
                class="success-icon"
              >
                <Check />
              </el-icon>
              <el-icon
                v-else-if="usernameAvailable === false"
                class="error-icon"
              >
                <Close />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱"
            size="large"
            prefix-icon="Message"
            clearable
            @blur="checkEmailAvailability"
          >
            <template #suffix>
              <el-icon v-if="emailChecking" class="is-loading">
                <Loading />
              </el-icon>
              <el-icon v-else-if="emailAvailable === true" class="success-icon">
                <Check />
              </el-icon>
              <el-icon v-else-if="emailAvailable === false" class="error-icon">
                <Close />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
            @input="checkPasswordStrength"
          />

          <!-- 密码强度指示器 -->
          <div v-if="registerForm.password" class="password-strength">
            <div class="strength-bar">
              <div
                class="strength-fill"
                :class="passwordStrength.level"
                :style="{ width: passwordStrength.percentage + '%' }"
              ></div>
            </div>
            <span class="strength-text" :class="passwordStrength.level">
              {{ passwordStrength.text }}
            </span>
          </div>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item prop="verificationCode">
          <div class="verification-input">
            <el-input
              v-model="registerForm.verificationCode"
              placeholder="请输入验证码"
              size="large"
              prefix-icon="Key"
              clearable
            />
            <el-button
              :disabled="!canSendCode || sendingCode"
              :loading="sendingCode"
              @click="sendVerificationCode"
            >
              {{ codeButtonText }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="agreeToTerms" size="large">
            我已阅读并同意
            <el-link type="primary" @click="showTerms"> 《用户协议》 </el-link>
            和
            <el-link type="primary" @click="showPrivacy">
              《隐私政策》
            </el-link>
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="register-button"
            :loading="loading"
            :disabled="!canRegister"
            @click="handleRegister"
          >
            {{ loading ? "注册中..." : "注册" }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 登录链接 -->
      <div class="login-link">
        <span>已有账号？</span>
        <el-link type="primary" @click="goToLogin"> 立即登录 </el-link>
      </div>
    </div>

    <!-- 用户协议对话框 -->
    <el-dialog
      v-model="termsVisible"
      title="用户协议"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="terms-content">
        <h3>1. 服务条款</h3>
        <p>
          欢迎使用CardCaptorSakura多人格AI聊天助手。在使用我们的服务之前，请仔细阅读本用户协议。
        </p>

        <h3>2. 用户责任</h3>
        <p>
          用户应当合法、合理地使用本服务，不得利用本服务进行任何违法违规活动。
        </p>

        <h3>3. 隐私保护</h3>
        <p>
          我们承诺保护用户的隐私信息，不会未经授权向第三方披露用户的个人信息。
        </p>

        <h3>4. 服务变更</h3>
        <p>我们保留随时修改或终止服务的权利，恕不另行通知。</p>

        <h3>5. 免责声明</h3>
        <p>
          本服务按"现状"提供，我们不对服务的准确性、可靠性或完整性作出任何保证。
        </p>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="termsVisible = false"> 关闭 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 隐私政策对话框 -->
    <el-dialog
      v-model="privacyVisible"
      title="隐私政策"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="privacy-content">
        <h3>1. 信息收集</h3>
        <p>
          我们可能收集您提供的个人信息，包括但不限于姓名、邮箱地址、使用偏好等。
        </p>

        <h3>2. 信息使用</h3>
        <p>我们使用收集的信息来提供、维护和改进我们的服务，以及与您沟通。</p>

        <h3>3. 信息共享</h3>
        <p>
          除非获得您的明确同意或法律要求，我们不会与第三方共享您的个人信息。
        </p>

        <h3>4. 数据安全</h3>
        <p>
          我们采取合理的安全措施来保护您的个人信息免受未经授权的访问、使用或披露。
        </p>

        <h3>5. 联系我们</h3>
        <p>
          如果您对本隐私政策有任何疑问，请通过邮箱联系我们：privacy@cardcaptorsakura.com
        </p>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="privacyVisible = false"> 关闭 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElForm } from "element-plus";
import { Check, Close, Loading } from "@element-plus/icons-vue";
import { useAuth } from "@/composables/useAuth";
import { authApi } from "@/api/services";
import { validatePassword } from "@/utils";
import type { FormInstance, FormRules } from "element-plus";
import type { RegisterRequest } from "@/types/user";

const router = useRouter();
const { register, loading } = useAuth();

// 表单引用
const registerFormRef = ref<FormInstance>();

// 注册表单
const registerForm = reactive<RegisterRequest>({
  username: "",
  email: "",
  password: "",
  confirmPassword: "",
  verificationCode: "",
});

// 状态
const agreeToTerms = ref(false);
const termsVisible = ref(false);
const privacyVisible = ref(false);
const usernameChecking = ref(false);
const emailChecking = ref(false);
const usernameAvailable = ref<boolean | null>(null);
const emailAvailable = ref<boolean | null>(null);
const sendingCode = ref(false);
const codeCountdown = ref(0);
const passwordStrength = ref({
  level: "weak",
  percentage: 0,
  text: "弱",
});

// 计算属性
const canSendCode = computed(() => {
  return (
    registerForm.email &&
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email) &&
    emailAvailable.value === true &&
    codeCountdown.value === 0
  );
});

const codeButtonText = computed(() => {
  if (sendingCode.value) return "发送中...";
  if (codeCountdown.value > 0) return `${codeCountdown.value}s后重发`;
  return "发送验证码";
});

const canRegister = computed(() => {
  return (
    registerForm.username &&
    registerForm.email &&
    registerForm.password &&
    registerForm.confirmPassword &&
    registerForm.verificationCode &&
    usernameAvailable.value === true &&
    emailAvailable.value === true &&
    agreeToTerms.value
  );
});

// 表单验证规则
const registerRules: FormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度为3-20个字符", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "用户名只能包含字母、数字和下划线",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, message: "密码至少8个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const result = validatePassword(value);
        if (!result.isValid) {
          callback(new Error(result.issues[0]));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  verificationCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码为6位数字", trigger: "blur" },
  ],
};

// 检查用户名可用性
const checkUsernameAvailability = async () => {
  if (!registerForm.username || registerForm.username.length < 3) {
    usernameAvailable.value = null;
    return;
  }

  try {
    usernameChecking.value = true;
    const available = await checkUsernameAvailable(registerForm.username);
    usernameAvailable.value = available;
  } catch (error) {
    usernameAvailable.value = false;
  } finally {
    usernameChecking.value = false;
  }
};

// 检查邮箱可用性
const checkEmailAvailability = async () => {
  if (
    !registerForm.email ||
    !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)
  ) {
    emailAvailable.value = null;
    return;
  }

  try {
    emailChecking.value = true;
    const available = await checkEmailAvailable(registerForm.email);
    emailAvailable.value = available;
  } catch (error) {
    emailAvailable.value = false;
  } finally {
    emailChecking.value = false;
  }
};

// 检查密码强度
const checkPasswordStrength = () => {
  const result = validatePassword(registerForm.password);

  switch (result.strength) {
    case "weak":
      passwordStrength.value = { level: "weak", percentage: 25, text: "弱" };
      break;
    case "medium":
      passwordStrength.value = {
        level: "medium",
        percentage: 60,
        text: "中等",
      };
      break;
    case "strong":
      passwordStrength.value = { level: "strong", percentage: 100, text: "强" };
      break;
  }
};

// 发送验证码
const sendVerificationCode = async () => {
  if (!canSendCode.value) return;

  try {
    sendingCode.value = true;
    await sendCode(registerForm.email);

    ElMessage.success("验证码已发送，请查收邮箱");

    // 开始倒计时
    codeCountdown.value = 60;
    const timer = setInterval(() => {
      codeCountdown.value--;
      if (codeCountdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  } catch (error: any) {
    ElMessage.error(error.message || "发送验证码失败");
  } finally {
    sendingCode.value = false;
  }
};

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return;

  try {
    const valid = await registerFormRef.value.validate();
    if (!valid) return;

    if (!canRegister.value) {
      ElMessage.warning("请完善注册信息");
      return;
    }

    const success = await register(registerForm);
    if (success) {
      ElMessage.success("注册成功，请登录");
    }
  } catch {
    // 注册失败
  }
};

// 显示用户协议
const showTerms = () => {
  termsVisible.value = true;
};

// 显示隐私政策
const showPrivacy = () => {
  privacyVisible.value = true;
};

// 跳转到登录页
const goToLogin = () => {
  router.push("/login");
};

// 监听用户名变化
watch(
  () => registerForm.username,
  () => {
    usernameAvailable.value = null;
  },
);

// 监听邮箱变化
watch(
  () => registerForm.email,
  () => {
    emailAvailable.value = null;
  },
);
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 450px;
  background: var(--el-bg-color);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
  backdrop-filter: blur(10px);
}

.register-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 8px;
}

.logo-image {
  width: 48px;
  height: 48px;
  border-radius: 8px;
}

.logo-text {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
}

.subtitle {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin: 0;
}

.register-form {
  margin-bottom: 24px;
}

.success-icon {
  color: var(--el-color-success);
}

.error-icon {
  color: var(--el-color-danger);
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  background: var(--el-border-color-lighter);
  border-radius: 2px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s;
}

.strength-fill.weak {
  background: var(--el-color-danger);
}

.strength-fill.medium {
  background: var(--el-color-warning);
}

.strength-fill.strong {
  background: var(--el-color-success);
}

.strength-text {
  font-size: 12px;
  min-width: 30px;
}

.strength-text.weak {
  color: var(--el-color-danger);
}

.strength-text.medium {
  color: var(--el-color-warning);
}

.strength-text.strong {
  color: var(--el-color-success);
}

.verification-input {
  display: flex;
  gap: 8px;
}

.verification-input .el-input {
  flex: 1;
}

.verification-input .el-button {
  white-space: nowrap;
}

.register-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
}

.login-link {
  text-align: center;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.login-link .el-link {
  margin-left: 4px;
}

.terms-content,
.privacy-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 0 8px;
}

.terms-content h3,
.privacy-content h3 {
  color: var(--el-text-color-primary);
  font-size: 16px;
  margin: 16px 0 8px 0;
}

.terms-content p,
.privacy-content p {
  color: var(--el-text-color-regular);
  font-size: 14px;
  line-height: 1.6;
  margin: 0 0 12px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-card {
    padding: 24px;
    margin: 0 16px;
  }

  .logo-text {
    font-size: 20px;
  }

  .verification-input {
    flex-direction: column;
  }
}

/* 暗色主题适配 */
.dark .register-container {
  background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
}
</style>
